using System;
using System.Data;
using System.Data.SqlClient;

namespace BoxBinary.AspectCache.Core.ErrorLogging
{
    /// <summary>
    /// 
    /// </summary>
    public class SqlClientLogger : ErrorLoggerBase
    {
        /// <summary>
        /// Saves the log.
        /// </summary>
        public override void SaveLog()
        {
            if (IsLoggingEnabled)
            {
                PopulateFromException();
                string[] mData = ErrorMetaData.GetSerialized();

                var sqlConnection = new SqlConnection(ConfigSection.Current.SqlClientLoggerConnectionString);
                var sqlCommand = new SqlCommand("SP_LogError", sqlConnection);
                try
                {
                    sqlConnection.Open();
                    sqlCommand.CommandType = CommandType.StoredProcedure;
                    sqlCommand.Parameters.AddWithValue("@Title", Title);
                    sqlCommand.Parameters.AddWithValue("@Body", Body);
                    sqlCommand.Parameters.AddWithValue("@MetaDataNames_CSV", mData[0]);
                    sqlCommand.Parameters.AddWithValue("@MetaDataValues_CSV", mData[1]);
                    sqlCommand.ExecuteNonQuery();
                }
                catch (Exception loggingException)
                {
                    try
                    {
                        // Try to log using the EmailErrorLogger
                        var backupLog = new EmailErrorLogger();
                        backupLog.StartNewLog(
                                                 new Exception(
                                                     string.Format("Could not log error to database! Error: '{0}'",
                                                                   loggingException.Message),
                                                     InnerException), HiddenFromUser);
                        backupLog.SaveLog();
                    }
                    catch
                    {
                        //TODO: Fallback from critical error
                    }
                }
                finally
                {
                    if (sqlConnection.State != ConnectionState.Closed)
                        sqlConnection.Close();
                    Clear();
                }
            }
        }
    }
}